//
//  ZTBaseNewsTableViewController.m
//  zhibo8
//
//  Created by zzt on 16/11/22.
//  Copyright © 2016年 zzt. All rights reserved.
//

#import "ZTBaseNewsTableViewController.h"
#import <AFNetworking/AFNetworking.h>
#import <MJExtension/MJExtension.h>
#import <MJRefresh/MJRefresh.h>
#import "ZTNewsCell.h"
#import "ZTNewsItem.h"

@interface ZTBaseNewsTableViewController ()<UIScrollViewDelegate>
@property (nonatomic, weak) UIScrollView *pageScrollView;
@property (nonatomic, weak) UIPageControl *pageControl;
@property (nonatomic ,weak) NSTimer *timer;
@property (nonatomic, strong)NSMutableArray *modelArray;
@property (nonatomic, weak) UILabel *pageTitleaLabel;
@property (nonatomic ,strong)NSString *imageUrl;
@property (nonatomic ,strong)NSString *labelTitle;
@property (nonatomic ,weak) UILabel *bottomLabel;
@property (nonatomic, strong)NSMutableArray *titleArray;

@property (nonatomic, strong) AFHTTPSessionManager *mgr;

@end

static int counts = 5;
static NSString * const ID = @"cell";

@implementation ZTBaseNewsTableViewController

- (AFHTTPSessionManager *)mgr
{
    if (_mgr == nil) {
        _mgr = [AFHTTPSessionManager manager];
        
        // 告诉AFN，支持接受 text/xml 的数据
        _mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
    }
    return _mgr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //添加广告轮播图
    [self addCarouselAD];
    
    //1.加载数据
//    [self loadData];
    
    //注册cell
    [self.tableView registerNib:[UINib nibWithNibName:@"ZTNewsCell" bundle:nil] forCellReuseIdentifier:ID];
    
    self.tableView.contentInset = UIEdgeInsetsMake(57, 0, 49, 0);
    
    self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
    
    
    // 添加上下拉刷新s
    [self setupRefreshView];
    
    // 请求更新数据
    [self.tableView.mj_header beginRefreshing];
    
    // 监听一次
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reload) name:@"reloadTheme" object:nil];
    
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)reload {
    // 判断只有显示到屏幕上,才需要刷新
    // 只要当前控件能获取到窗口,就表示显示到屏幕
    if (self.view.window) {
        [self.tableView.mj_header beginRefreshing];
    }
}

#pragma mark - 添加上下拉刷新
- (void)setupRefreshView
{
    // 请求成功,一定要告诉MJRefresh,请求完成
    // 添加下拉刷新
    MJRefreshNormalHeader *headerView = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    headerView.automaticallyChangeAlpha = YES;
    self.tableView.mj_header = headerView;
    
    // 添加上拉刷新
        MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        footer.automaticallyHidden = YES;
        self.tableView.mj_footer = footer;
}


#pragma mark - 加载数据
- (void)loadNewData {
    
    // 取消上拉刷新
    [self.mgr.tasks makeObjectsPerformSelector:@selector(cancel)];

    //1.创建管理者
//  AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    
    //2.拼接参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"appname"] = @"zhibo8";
    parameters[@"platform"] = @"ios";
    parameters[@"version_code"] = @"4.3.0";
    parameters[@"_only_care"] = @"1";
    
    //3.发送请求
    [self.mgr GET:self.url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *responseObject) {
        
        // 结束刷新
        [self.tableView.mj_header endRefreshing];
        
        //1.获取字典数组
        NSArray *dictArray = responseObject[@"toplist"];
        
        //2.字典数组转模型数组
        _modelArray = [ZTNewsItem mj_objectArrayWithKeyValuesArray:dictArray];
        
        //3.刷新表格
        [self.tableView reloadData];
        
        //移除之前添加的imageView
        [_pageScrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        
        NSMutableArray *titleArray = [NSMutableArray array];
        for (NSUInteger i = 0; i < 5; i++) {
            self.imageUrl = dictArray[i][@"thumbnail"];
            
            NSString *labelTitle = dictArray[i][@"shortTitle"];
            [titleArray addObject:labelTitle];
            //给轮播图赋值
            [self setupImageviewWithSting:_imageUrl NSUInteger:i labelTitle:self.labelTitle];
        }
        
        _titleArray = titleArray;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error){
        
    }];
}

#pragma mark - 加载数据
- (void)loadMoreData {
    
    //NBA新闻和足球新闻界面只能显示头条,不能加载更多
    // 取消上拉刷新
    [self.mgr.tasks makeObjectsPerformSelector:@selector(cancel)];
    // 结束刷新
    [self.tableView.mj_footer endRefreshing];
    self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
        
}


#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _modelArray.count;
}


- (ZTNewsCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ZTNewsCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    cell.item = _modelArray[indexPath.row];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}


//广告轮播
-(void)addCarouselAD {
    
    UIScrollView *pageScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 57, [UIScreen mainScreen].bounds.size.width, 220)];
    _pageScrollView = pageScrollView;
    _pageScrollView.showsHorizontalScrollIndicator = NO;
    
    pageScrollView.delegate = self;
    
    pageScrollView.backgroundColor = [UIColor redColor];
    self.tableView.tableHeaderView = pageScrollView;
    
    //添加长条放PageControl和添加页面标题
    [self addBottomLabel];
    
    //2.添加PageControl
    [self addPageControl];
    
    //3.添加页面标题
    [self addPageTitleaLabel];
    
    //4.开启定时器
    [self startTimer];
}

//添加长条放PageControl和添加页面标题
- (void)addBottomLabel {
    UILabel *bottomLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 190, self.view.bounds.size.width, 30)];
    _bottomLabel = bottomLabel;
    bottomLabel.backgroundColor = [UIColor lightGrayColor];
    
    //设置UILabel的alpha
    _bottomLabel.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4];
    [self.view addSubview:bottomLabel];
}


- (void)addPageControl {
    
    UIPageControl *pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(_pageScrollView.bounds.size.width - 80, _pageScrollView.bounds.size.height - 22.5, 80, 15)];
    _pageControl = pageControl;
    
    //设置当前页面和费当前页面的pageControl的原点颜色
    pageControl.pageIndicatorTintColor = [UIColor greenColor];
    pageControl.currentPageIndicatorTintColor = [UIColor blueColor];
    
    // 1.设置pageControl单页的时候是否隐藏
    pageControl.hidesForSinglePage = YES;
    
    // 2.设置pageControl显示的图片(KVC)
    [pageControl setValue:[UIImage imageNamed:@"current"] forKeyPath:@"_currentPageImage"];
    [pageControl setValue:[UIImage imageNamed:@"other"] forKeyPath:@"_pageImage"];
    
    // 3.设置总页数(一定要在初始化UIPageControl对象时设置页数,不然不显示!!!!!!!!!!!!)
    _pageControl.numberOfPages = counts;
    
    [self.view addSubview:pageControl];
    
}

//添加页面标题
- (void)addPageTitleaLabel {
    UILabel *pageTitleaLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, _pageScrollView.bounds.size.height - 22.5, 300, 15)];
    _pageTitleaLabel = pageTitleaLabel;
    pageTitleaLabel.textColor = [UIColor whiteColor];
    pageTitleaLabel.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:pageTitleaLabel];
}


- (void)setupImageviewWithSting:(NSString*)imageUrl NSUInteger:(NSUInteger)i labelTitle:(NSString *)labelTitle{
    
    // 1.根据图片名数据创建ImageView添加到scrollView中
    CGFloat scrollViewW = _pageScrollView.frame.size.width;
    CGFloat scrollViewH = _pageScrollView.frame.size.height;
    
    NSUInteger count = counts;
    
    UIImageView *imageView = [[UIImageView alloc] init];
    NSURL *url = [NSURL URLWithString:_imageUrl];
    NSData *data = [NSData dataWithContentsOfURL:url];
    imageView.image = [UIImage imageWithData:data];
        
    NSLog(@"%@",_imageUrl);
    imageView.frame = CGRectMake(i * scrollViewW, 0, scrollViewW, scrollViewH);
    [_pageScrollView addSubview:imageView];
    
    // 2.设置contentSize
    //  0表示垂直方向不能滚动
    _pageScrollView.contentSize = CGSizeMake(count * scrollViewW, 0);
    
    // 3.设置总页数(一定要在初始化UIPageControl对象时设置页数,在这里设置不显示!!!!!!!!!!!!)
    // _pageControl.numberOfPages = count;
    
    _pageControl.currentPage = 0;
    
}

#pragma mark - 定时器的相关方法
- (void)startTimer {
    
    // 返回一个会自动执行任务的定时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(nextPage:) userInfo:@"123" repeats:YES];
    
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)stopTimer {
    [self.timer invalidate];
    
}


/**
 *  滚动到下一页
 */
- (void)nextPage:(NSTimer *)timer{
    // 计算下一页页码
    NSInteger page = self.pageControl.currentPage + 1;
    
    // 超过最后一页
    if (page == counts) {
        page = 0;
    }
    // 滚动到下一页
    [_pageScrollView setContentOffset:CGPointMake(page * _pageScrollView.frame.size.width, 0) animated:YES];
    
    _pageTitleaLabel.text = _titleArray[page];
    
}


#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    // 计算页码
    NSUInteger page = (int)(scrollView.contentOffset.x / scrollView.frame.size.width + 0.5);
    
    // 设置页码
    _pageControl.currentPage = page;
    _pageTitleaLabel.text = _titleArray[page];
    
}

/**
 *  用户即将开始拖拽scrollView,停止定时器
 */
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self stopTimer];
}

/**
 *  用户已经停止拖拽scrollView,开启定时器
 */
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [self startTimer];
}

@end


